Skip to content

9.24 实体/全局查询筛选器

9.24.1 查询筛选器

通常,我们系统中有一些维护字段,如 IsDeleted 字段,这个字段用来标识用户已经删除的数据,那么我们需要每次查询数据的时候带上这个字段,避免查询出不该出现的数据。

Furion 提供非常灵活方便的全局查询筛选器,能够应用到每一次查询中。

9.24.2 多种筛选器配置

9.24.2.1 单表筛选器

单表筛选器就是只针对特定实体进行筛选操作,使用简单,只需要在继承 IEntityTypeBuilder<TEntity> 接口并实现即可,如:

using Furion.DatabaseAccessor;  
using Microsoft.EntityFrameworkCore;  
using Microsoft.EntityFrameworkCore.Metadata.Builders;  
using System;  

namespace Furion.Core  
{  
    public class Person : Entity, IEntityTypeBuilder<Person>  
    {  
        public Person()  
        {  
            CreatedTime = DateTime.Now;  
            IsDeleted = false;  
        }  

        public string Name { get; set; }  

        public int Age { get; set; }  

        public string Address { get; set; }  

        public void Configure(EntityTypeBuilder<Person> entityBuilder, DbContext dbContext, Type dbContextLocator)  
        {  
            entityBuilder.HasQueryFilter(u => !u.IsDeleted);  
        }  
    }  
}  

9.24.2.2 全局筛选器

全局筛选器可以配置所有实体应用筛选器中,无需一个一个去配置。使用方法稍微有些复杂,需要动态构建 Lambda 表达式。

实现全局筛选器依赖于 IModelBuilderFilter 接口,该接口提供两个方法:

  • OnCreating:实体构建之前
  • OnCreated:实体构建之后

通过实现这两个方法即可配置全局过滤器,如:

using Furion.DatabaseAccessor;  
using Microsoft.EntityFrameworkCore;  
using Microsoft.EntityFrameworkCore.Metadata.Builders;  
using System;  
using System.Linq.Expressions;  

namespace Furion.EntityFramework.Core  
{  
    [AppDbContext("Sqlite3ConnectionString")]  
    public class FurionDbContext : AppDbContext<FurionDbContext>, IModelBuilderFilter  
    {  
        public FurionDbContext(DbContextOptions<FurionDbContext> options) : base(options)  
        {  
        }  

        public void OnCreating(ModelBuilder modelBuilder, EntityTypeBuilder entityBuilder, DbContext dbContext, Type dbContextLocator)  
        {  
            // 获取元数据  
            var metadata = entityBuilder.Metadata;  

            // 设置软删除表达式  
            var fakeDeleteQueryFilterExpression = FakeDeleteQueryFilterExpression(entityBuilder, dbContext);  
            if (fakeDeleteQueryFilterExpression == null) return;  

            entityBuilder.HasQueryFilter(fakeDeleteQueryFilterExpression);  
        }  
    }  
}  

小建议如果对动态构建 LambdaExpression 不熟悉的朋友,可以使用 System.Linq.Dynamic.Corehttps://github.com/zzzprojects/System.Linq.Dynamic.Core

9.24.3 反馈与建议

与我们交流给 Furion 提 Issue